package com.lg.cms.controller.news;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.entity.User;
import com.lg.cms.service.CategoryService;
import com.lg.cms.service.TagsService;
import com.lg.cms.service.UserService;
import com.lg.cms.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Description: 注册
 * @Author: wuyuhang
 * @create: 2020-10-09 08:29
 */
@Controller
public class RegisterController {

    @Autowired
    UserService userService;

    @Autowired
    CategoryService categoryService;

    /**
     * 用户注册页面
     * @return
     */
    @GetMapping("/register")
    public String get(Model model){
        model.addAttribute("categoryList", categoryService.getList());
        return "/news/wyh-test/register";
    }

    /**
     * 用户注册post
     * @param user
     * @param code
     * @param session
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public R<?> register(User user, String code, HttpSession session){
        String sessionCode = (String)session.getAttribute("cms_code");
        code = Md5Util.textToMd5(code);
        if(!code.equals(sessionCode)){
            return R.failed("验证码错误");
        }
        if(!user.checkData()){
            return R.failed("数据验证失败, 请按规范输入数据");
        }
        //查询用户名是否存在
        User name = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if(name != null){
            return R.failed("用户名已存在");
        }
        User nickname = userService.getOne(new QueryWrapper<User>().eq("nickname", user.getNickname()));
        if(nickname != null){
            return R.failed("昵称已存在");
        }
        //密码加密
        user.setPassword(Md5Util.textToMd5(user.getPassword()));
        boolean result = userService.save(user);
        if(!result){
            return R.failed("注册失败");
        }
        return R.ok(user);

    }
}